import React, { useState ,useEffect} from 'react';
import '@/assets/css/dashboard.css'
import {useSelector,useDispatch} from 'react-redux'
//引入二级路由组件
import SecondRules from '../../router/secondRules';
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    UploadOutlined,
    UserOutlined,
    VideoCameraOutlined,
    PieChartOutlined,
    DesktopOutlined,
    ExclamationCircleOutlined
  } from '@ant-design/icons';
  import { Layout, Menu, theme ,Button,Modal, message} from 'antd';
  import { Link,useHistory,useLocation } from 'react-router-dom';
  import {getadmininfo,jwtPreCheck} from '@/api/dashboard'
  const { Header, Sider, Content } = Layout;
 


const Dashboard = () => {
    //控制左侧菜单折叠的变量
    const [collapsed, setCollapsed] = useState(false);
    const {
    token: { colorBgContainer },
    } = theme.useToken();


    // 获取redux仓库中的acl
    const {acl} = useSelector((state)=>state)
    console.log(acl);
    function getItem(label, key, icon, children, type) {
        return {
          key,
          icon,
          children,
          label,
          type,
        };
      }
    //   处理acl数据，用于渲染左侧菜单栏
    const  newArr =[]
    acl.map((item,index)=>{
        if(item.children.length!=0){
            //当该菜单有二级菜单时
            newArr.push(getItem(item.auth_name,item.auth_path,<PieChartOutlined />,item.children.map((item2,index2)=>{
                // 只渲染 is_nav为1 的菜单项
                // 渲染二级菜单
                if(item2.is_nav==1){
                    return getItem(<Link to={item2.auth_path}>{item2.auth_name}</Link>,item2.auth_path)
                }
                
            })))
        }else{
            //当该菜单只有1级菜单时
            newArr.push(getItem(<Link to={item.auth_path}>{item.auth_name}</Link>,item.auth_path,<DesktopOutlined />))
        }
    })
    //定义退出登录的接口：清除登录时存储的信息,并返回登录页面
    const dispatch = useDispatch()
    const his = useHistory()
    const loginOut=()=>{
        // 清除jwt
        localStorage.removeItem('jwt')
        // 清除ACL
        dispatch({type:'updateAcl',payload:[]})
        localStorage.removeItem('persist:root')
        // 返回登录页面 
        his.push('/login')
    }
    const confirm = () => {
        Modal.confirm({
          title: '确认要退出登录吗？',
          icon: <ExclamationCircleOutlined />,
          content: '退出登录 ...',
          okText: '确认',
          cancelText: '取消',
          onOk:()=>{
            loginOut()
          }
        });
      };

      //调用获取用户登录信息接口，用来徐然头部用户信息数据
      const [userinfo, setuserinfo] = useState('');
      const [islogin, setIslogin] = useState(false)
      useEffect(() => {
        getadmininfo().then(res=>{
            console.log('userInfo',res);
            if(res.data.errNo==0){
                setuserinfo(res.data.accountInfo)
            }
        })

        // 防跳墙功能,调用jwt预检接口
        
        jwtPreCheck().then(res=>{
          console.log('jwt预检',res);
          if(res.data.errNo!=0){
              //未登录
              message.error('请先登录',1,()=>{
                his.push('/login')
              })
          }else{
            //已经登录
            setIslogin(true)
            // islogin可以用做页面是否渲染的判断，以优化性能
          }
        })
        
      }, []);
      // 设置菜单栏默认选中的项，利用useLocation()这个hook
      // useLocation可以获取当前的地址对象信息
      const loc = useLocation()
      console.log('location',loc);
    
    return (
      <>
      {islogin?       <Layout>
        <Sider trigger={null} collapsible collapsed={collapsed}>
          <div className="logo" ></div>
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={[loc.pathname]}//设置菜单栏默认选中的项
            // 初始展开的 SubMenu 菜单项 key 数组
            defaultOpenKeys={[loc.pathname.substring(0,loc.pathname.lastIndexOf('/'))]}		
            items={newArr}
          />
        </Sider>
        <Layout className="site-layout">
          <Header
            style={{
              padding: 0,
              background: colorBgContainer,
              display:'flex',
              alignItems:'center'
  
            }}
          >
            {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: 'trigger',
              onClick: () => setCollapsed(!collapsed),
            })}
            <div style={{
              display:'flex',
              flex:1,
              justifyContent:'space-between',
              alignItems:'center',
              paddingLeft:'10px',
              paddingRight:'15px'
  
            }}>
              <span>您好，{userinfo.username}/{userinfo.role}</span>
              <Button onClick={confirm}>退出登录</Button>
            </div>
            
          </Header>
          <Content
            style={{
              margin: '24px 16px',
              padding: 24,
              minHeight: 280,
              background: colorBgContainer,
            }}
          >
            {/* 放二级路由的坑 */}
            <SecondRules></SecondRules>
          </Content>
        </Layout>
      </Layout>:<></>}
      </>
    );
}

export default Dashboard;
